﻿using System;
using System.Text;

namespace Plugins.Samples.Internal
{
    static class PiAlgorithm
    {
        /// <summary> 
        /// Calculates a given number of hexadecimal digits of PI from the given start position. 
        /// </summary> 
        /// <param name="start">Hexadecimal position to start calculating hexadecimal digits from.</param> 
        /// <param name="length">Number of hexadecimal digits to calculate. Needs to be multiple of 10.</param> 
        /// <returns>Requested hexadecimal digits of PI.</returns> 
        public static string Calculate(int start, int length)
        {
            if (start < 0)
                throw new ArgumentException("start");

            if (length < 0 || length % 10 != 0)
                throw new ArgumentException("length");

            StringBuilder sb = new StringBuilder();

            // 
            // Calculate in chunks of 10 given our precision. 
            // 
            for (int pos = start; pos < start + length; pos += 10)
            {
                double val = 4 * Pi.Sum(1, pos) - 2 * Pi.Sum(4, pos) - Pi.Sum(5, pos) - Pi.Sum(6, pos);
                val = val - (int)val + 1;
                sb.Append(Pi.ToHex(val));
            }

            return sb.ToString();
        }
    }
}
